const express = require('express');
const router = express.Router();
const {login, register} = require('../controller/user');
const {SuccessModel, ErrorModel} = require('../model/resModel');
const loginCheck = require('../middleWare/loginCheck');
const registerCheck = require('../middleWare/registerCheck');
const rootCheck = require('../middleWare/rootCheck');

router.post('/login', function(req, res, next) {
  const { username, password } = req.body;
  const result = login(username, password);
  return result.then(data => {
    if(data.username) {
      // 设置 session
      req.session.username = data.username;
      req.session.realname = data.realname;
      res.json(new SuccessModel());
      return ;
    }
    res.json(new ErrorModel('登录失败'))
  })
});

router.post('/register', registerCheck, function(req, res, next) {
  const {username, password} = req.body;
  const result = register(username, password);
  return result.then(data => {
    console.log('注册成功', data);
    res.json(new SuccessModel("注册成功"));
  }).catch(err => {
    console.log('注册失败', err);
    res.json(Promise.reject(new ErrorModel('注册失败')));
  })
});

router.get('/login-check',  (req, res, next) => {
  if (req.session.username) {
    res.json(new SuccessModel(req.session.username));
    return;
  }
  res.json(new ErrorModel('未登录'));
});

router.get('/logout', loginCheck, (req, res, next) => {
  req.session.username = '';
  req.session.realname = '';
  res.json(new SuccessModel('退出登录成功'));
});

router.get('/rootCheck', rootCheck, (req, res, next) => {
  res.json(new SuccessModel('当前账号具备相关权限'));
});

module.exports = router;
